﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using AncientLand.Service.Entity;
using AncientLand.Service.IBiz;

namespace AncientLand.Controllers
{
   public class WeddingAdminController:  Controller
    {

       private readonly IWeddingCategoryBiz _service;

       public WeddingAdminController(IWeddingCategoryBiz service)
      {
          this._service = service;
      }

     [Authorize]
      public ActionResult WeddingCategoryList(int? page = 1)
     {
         ViewBag.Model = "ShowCase";

           var size = Convert.ToInt16(System.Configuration.ConfigurationSettings.AppSettings["AdminpageSize"]);

            var totalRecord = 0;
            var categorys = _service.GetCategoryByPages(out totalRecord,pageIndex:page.GetValueOrDefault(),pageSize:size,orderFiled:"");

            var item = new PageItem()
                           {
                               CurrentPage = page.GetValueOrDefault(),
                               TotalRecords = totalRecord,
                               TotalPages= (totalRecord % size == 0) ? totalRecord / size : totalRecord / size + 1,
                               ControllerName = "WeddingAdmin",
                               ActionName = "WeddingCategoryList"
                           };

            var viewModels = new Pager<WeddingCategory>() { DataSource = categorys, Item = item };

            return View(viewModels);
       }

      [Authorize]
      [HttpPost]
      public ActionResult WeddingCategoryAdd(FormCollection forms)
      {

          if (forms != null && !string.IsNullOrEmpty(forms["txtCategoryName"]))
          {
              var categoryName = forms["txtCategoryName"].Trim();
              var category = new WeddingCategory() { Name = categoryName, ThumbnailPath = "/images/NoPicture.jpg" };
              category.CreatedTime = DateTime.Now;
              _service.Create(category);

              var directoryInfo = new DirectoryInfo(Server.MapPath("~/UpFiles/婚纱/" + categoryName + "/"));
              if (!directoryInfo.Exists)
              {
                  directoryInfo.Create();
              }
              directoryInfo = new DirectoryInfo(Server.MapPath("~/UpFiles/婚纱/" + categoryName + "/Thumbnail/"));
              if (!directoryInfo.Exists)
              {
                  directoryInfo.Create();
              }
          }

          return RedirectToAction("WeddingCategoryList");
      }

       [Authorize]
       public ActionResult DeleteWeddingCategory(int id, string name)
       {
           _service.Delete(id);

           DeleteFolder(Server.MapPath("~/UpFiles/婚纱/" + name + "/"));

           return RedirectToAction("WeddingCategoryList");
       }

       [Authorize]
       public ActionResult ShowWeddingCategory(int id, string name)
       {
           ViewBag.Model = "ShowCase";
           ViewBag.CategoryId = id;
           var category= _service.GetById(id);
           ViewBag.ThumPath = category.ThumbnailPath;
           List<string> model = GetModel("~/UpFiles/婚纱/", name);
           return View(model);
       }

       [Authorize]
       public ActionResult DeleteWeddingPicture(string name, string category,int categoryId)
       {
           ViewBag.Model = "ShowCase";
           var xPath = "~/UpFiles/婚纱/" + category + "/" + name;
           var thumbnailImage = "~/UpFiles/婚纱/" + category + "/Thumbnail/" + name;
           System.IO.FileInfo pictorialInfo = new FileInfo(Server.MapPath(xPath));
           if (pictorialInfo.Exists)
           {
               pictorialInfo.Delete();
           }
           pictorialInfo = new FileInfo(Server.MapPath(thumbnailImage));
           if (pictorialInfo.Exists)
           {
               pictorialInfo.Delete();
           }

           return RedirectToAction("ShowWeddingCategory", new { id = categoryId, name = category }); 
       }


       [Authorize]
       public ActionResult SetAsFrontCover(string name,int categoryId)
       {
           var category = _service.GetById(categoryId);
           category.ThumbnailPath = "/UpFiles/婚纱/" + category.Name + "/Thumbnail/" + name;
           _service.Update(category);

           return RedirectToAction("WeddingCategoryList");
       }


       [ChildActionOnly]
       //[OutputCache(Duration = 3600)]
       public PartialViewResult _categoryAdmin(string photoType)
       {
           ViewBag.PhotoType = photoType;


           return PartialView("_categoryAdmin", _service.GetAll());
       }

       private List<string> GetModel(string xPath, string category)
       {
           if (string.IsNullOrEmpty(category))
           {
               System.IO.DirectoryInfo pictorialInfo = new DirectoryInfo(Server.MapPath(xPath));
               if (pictorialInfo.Exists)
               {
                   DirectoryInfo[] folders = pictorialInfo.GetDirectories();
                   if (folders.Count() > 0)
                   {
                       category = folders[0].Name;
                   }
               }
           }
           category = Server.UrlDecode(category);

           string filePath = xPath + category + "/";
           
           ViewBag.Category = category;
           ViewBag.Path = filePath;
           
           List<string> model = new List<string>();
           System.IO.DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath(filePath));
           if (directoryInfo.Exists)
           {
               FileInfo[] fileInfos = directoryInfo.GetFiles();
               if (fileInfos.Count() > 0)
               {
                   foreach (FileInfo fileInfo in fileInfos)
                   {
                       if (fileInfo.Extension.ToLower() == ".jpg" || fileInfo.Extension.ToLower() == ".gif" || fileInfo.Extension.ToLower() == ".png")
                       {   
                           model.Add(fileInfo.Name);
                       }
                        
                   }
               }
           }
           return model;
       }

       private void DeleteFolder(string dir)
       {
           if(Directory.Exists(dir))
           {
               foreach (var fileSystemEntry in Directory.GetFileSystemEntries(dir))
               {
                   if(System.IO.File.Exists(fileSystemEntry))
                   {
                       System.IO.File.Delete(fileSystemEntry);
                   }
                   else
                   {
                       DeleteFolder(fileSystemEntry);
                   }
               }
               Directory.Delete(dir,true);
           }
       }
    }
}
